Sinclair BASIC is a dialect of the programming language BASIC used in the 8-bit from Sinclair Research, Timex Sinclair and Amstrad. The Sinclair BASIC interpreter was written by Nine Tiles Networks Ltd.
Designed initially to run in only 1 KB of RAM, the system makes a number of decisions to lower memory usage. This led to one of Sinclair BASIC's most notable features, that the keywords were entered using single keystrokes; each of the possible keywords was mapped to a key on the keyboard, when pressed, the token would be placed into memory while the entire keyword was printed out on-screen. This made code entry easier whilst simplifying the Parsing.
The original ZX80 version supported only integer mathematics, which partially made up for some of the memory-saving design notes which had negative impact on performance. When the system was ported to the ZX81 in 1981, a full floating point implementation was added. This version was very slow, among the slowest BASICs on the market at the time, but given the limited capabilities of the machine, this was not a serious concern. The low speed was not mainly due to an inefficient interpreter though, it was an effect of the fact that 70-80% of the machine cycles were consumed by the video hardware. So the Z80 in the ZX81 clocked at 3.25 MHz was "in effect" running at well below 1 MHz from the perspective of the BASIC system.
Performance became a more serious issue with the release of the ZX Spectrum in 1982, which ran too slowly to make full use of the machine's new features. This led to an entirely new BASIC for the following Sinclair QL, as well as a number of 3rd-party BASICs for the Spectrum and its various clones. The original version continued to be modified and ported in the post-Sinclair era.
Even before the ZX80 was introduced in February 1980, the constant downward price-pressure in the industry was allowing the already inexpensive design to be further reduced in complexity and cost. In particular, many of the separate circuits in the ZX80 were re-implemented in a single uncommitted logic array from Ferranti, which allowed the price to be reduced to only £49.95 while increasing the size of the ROM to 8 KB. This work was assigned to Steve Vickers, who joined Nine Tiles in January 1980. Whilst Grant worked on the code interfacing with hardware, Vickers used the larger space to introduce floating-point arithmetic and a suite of trigonometry functions, which were expected of any BASIC from that era, producing 8K BASIC. The initial version did not support the ZX Printer and had a bug in its square root function. Nine Tiles provided a new version to address these, but Sinclair was slow to include the new version in the ROMs. The new ROMs were eventually offered to owners of the earlier ZX80 as well.
When Sinclair lost the contest to build the BBC Computer, he moved ahead with plans to produce a low-cost colour-capable machine that emerged as the ZX Spectrum of April 1982. ROM space would once again be increased, this time to 16 KB. In keeping with his philosophy of making systems for the lowest possible expenditure, Sinclair wanted the absolute minimum changes to the existing 8K BASIC. Although Nine Tiles felt that something much better would be needed for the new machine, the schedule would not allow it, and yet another expansion of the original code was produced. Due to the RAM also being increased, to 48 KB, this version was known as 48K BASIC and eventually 48 BASIC with the introduction of the ZX Spectrum 128 at which time the 16 KB Spectrum was no longer sold and most existing ones in use had been upgraded to 48 KB. The new version was available near the end of 1981, but it was "depressingly slow" and "snail like". Additionally, as no prototypes were available until the end of the year, it lacked support for the new line of peripherals Sinclair was planning.
In February 1982, Nine Tiles began to have disagreements with Sinclair over owed royalties for the various manuals that Nine Tiles had produced. Around the same time, Vickers and his Sinclair counterpart, Richard Altwasser, left their respective companies to start the Jupiter Ace project. When the Spectrum was launched the ROM was still not complete, and although Nine Tiles continued working on it until April 1982, by that point 75,000 Spectrums had already been sold and the project was cancelled. The missing functionality was later added by additional code in the ZX Interface 1. After Nine Tiles and Sinclair went their own ways, several new versions of 48 BASIC were created.
In 1983, as part of introducing the Spectrum to the US market as the TS2068, Timex Sinclair modified it as T/S 2000 BASIC. The new version was incapable of running many Spectrum programs due to the memory location of machine's functions moving. A similar, but somewhat more compatible version, was introduced as part of the Spanish Spectrum 128 of 1985, 128 BASIC.
Amstrad purchased Sinclair Research in 1986. As Sinclair had never owned the copyright to the language, Amstrad had to arrange a new license with Nine Tiles. Several other versions also appeared in this period as various extensions and clones of the Spectrum were introduced. These included +3 BASIC, BASIC64 and Timex Extended Basic.
As of 2015, interpreters exist for modern , and older systems, that allow Sinclair Basic to be used easily.
In contrast to most machines of the era, the editor does not allow freeform editing at any point on the screen. Instead, when the user presses , the current line of code is copied back to the bottom of the screen. The user can move horizontally through this line using the and commits their changes by pressing again. In contrast, on machines like the Commodore 64 or Atari 8-bit computers, the up and down keys can be used to move among the lines in the program and edit them in-place.
The most notable feature of the editor is that keywords are entered using single keystrokes. For instance, on the ZX81, the key on the keyboard would cause the entire keyword to be entered into the currently editing line. Once a keyword has been entered, the cursor changes to an "L" to indicate what follows will be interpreted as normal text. For instance, pressing again at this point would enter a single letter "P".
Keys generally had two separate keywords assigned to them one above it and one below. Pressing the key in "K" mode would enter the keyword above the key, like for . If the system was in "L" mode, one could return to "K" by pressing the shift key the systems did not initially support lowercase text, so the shift was not otherwise needed. The keywords below the keys required a second keystroke, , which put the editor into "function mode", changing the cursor to an "F". Entering common code often resulted in a significant number of keystrokes.
The system has the advantage of representing all multi-character keywords as a single character in memory, which was a significant savings in the early machines that shipped with only 1 KB of RAM. This single-character representation included multi-character items like . This has the added advantages of simplifying the runtime, as it can immediately determine whether a character in the source code is a keyword or text, and also means that keywords are never entered directly, meaning that one can, for instance, have a variable named "PRINT", as the system can determine that it is not the same as the keyword.
As the systems evolved and added new keywords, the entry system became increasingly difficult to use. 48 BASIC in the Spectrum required every key to host up to four keywords. Entering keywords was a time-consuming process of looking over the relatively small type on the keyboard for the appropriate key, and then correctly entering the multiple keystrokes needed to enter it properly. For instance, entering required one to type to access extended mode (later models include a separate key), keeping held down, and then and pressing . To improve the complex entry on the Spectrum, the keywords were colour-coded to indicate the required mode:
This concept had run its course, and later machines running 128 BASIC (ZX Spectrum 128, +2, +3, +2A, and +2B) featured a more traditional editor where the user typed-in the keyword as individual characters, similar to other home computers of the era. This required a new tokenizer to convert the line into a similar internal format.
The resulting in-memory storage of the program was otherwise similar to Microsoft BASIC, in that only the keywords are presented as tokens, while non-keywords like string and numeric constants and variable names are left in their original typed-in format. However, that typed-in format was not ASCII, but an internal character code that contains both printable characters and the keyword tokens. Although portions of the table, the capital letters A to Z, for instance, are in the same order as in ASCII, their characters correspond to different numeric values, i.e. their ' offset from zero is different from ASCII's offset of 65. Other characters, like punctuation, may have been moved about even more. The ZX Spectrum character set is the most prominent example of such a character code. Related computers running Sinclair BASIC used similar variants, e.g. the ZX80 or ZX81 character sets. All of these different but related character sets included Sinclair BASIC tokens.
The first byte for a variable entry always held the type in the first three bits, and the first character of the name in the next five bits. As was the case in most microcomputer dialects, A, A$, A() and A$() were all different variables and could store different values. Most variables could only have a single-character name; the exception are numeric variables (not arrays), where an alternate format held the first character of the name in those same five bits, but was then followed by additional characters ending with one with its high-bit set. Long variable names were whitespace-independent, and case-insensitive in later versions, so
The downside to this approach is that scanning the table to look up the value of a variable reference is more complex. In addition to testing whether the name matches using the subset of the first byte, if the entry is not the one that is being looked for, the type has to be read from the upper three bits and then the next location of a variable in storage calculated using the type. For instance, if the program encounters the variable "A" and the table starts with the entry for "B$", it fails to match A with B, then reads the type to see it is a string, and then has to read the following length byte and skip forward by that amount of bytes to find the next entry in the table. To make this somewhat easier, arrays also stored a two-byte length, so the entire structure could be skipped over more easily.
A unique feature was the "short float", or integer type. Any numeric variable could store either type, the storage itself did not change and used 5 bytes in either case. Integers were indicated by setting the exponent byte to zero, while floating-point values were stored with an excess-128 format exponent. This meant that it could not store zero as a float and lost one possible exponent magnitude. It also did not use any less memory, as the values were still 5-byte in memory. The advantage to this format is performance; the math library included tests to look for the zero exponent, and if it was seen, it would not attempt to perform various operations on the remaining 3 bytes under certain conditions.
Unique code points are assigned in the ZX80 character set, ZX81 character set and ZX Spectrum character set for each keyword or multi-character operator, i.e. (2 TO ), <=, >=, <> (tokenized on the ZX81 only), "" (replaced with ** on the Spectrum). These are expanded by referencing a token table in ROM. Thus, a keyword uses one byte of memory only, a significant saving over traditional letter-by-letter storage. This also meant that the BASIC interpreter could quickly determine any command or function by evaluating one byte, and that the keywords need not be reserved words like in other BASIC dialects or other programming languages, e.g., it is allowed to define a variable named ↑ and output its value with PRINT. This is also related to the syntax requirement that every line start with a command keyword, and pressing the one keypress for that command at the start of a line changes the editor from command mode to letter mode. Thus, variable assignment requires
128 BASIC, present on ZX Spectrum 128, +2, +3, +2A, and +2B, stored keywords internally in one-byte code points, but used a conventional letter-by-letter BASIC input system. It also introduced two new commands:
The original Spanish ZX Spectrum 128 included four additional BASIC editor commands in Spanish, one of which was undocumented:
Unlike the ANCHO, LEFT$() and MID$() functions used in the ubiquitous Microsoft BASIC dialects for home computers, substrings in Sinclair BASIC are accessed with a parentheses notation. For example, gives a substring starting with the 5th and ending with the 10th character of the variable RIGHT$(), whereas and A$(5 TO 10) respectively returns substrings from the left, right or a single character.
| a$ | a$( TO 5) | then | Function | Returns the absolute value of a$(5 TO ) |
| a$(5) | ABS | then | Function | Returns the arccosine of number |
| number | Logical operator | Returns true if both conditions on either side of the ACS keyword are true, else returns false | ||
| number | number | then | Function | Returns the arcsine of AND |
| AND | ASN | Other | Used in a number statement to print at the line and column specified; for example, number puts a star in column 10 of line 5. | |
| AT | line, column; | then | Function | Returns the arctangent of PRINT |
| PRINT AT 5,10;"*" | ATN | then | Function | Returns a byte containing information on the colours of the text cell on the screen, corresponding to the specified number and number; note that, unlike most Sinclair BASIC keywords, the parentheses are required; the first three bits indicate the ink (foreground) colour, the fourth, fifth and sixth bits the paper (background) colour, the seventh bit whether the colours are bright or not, and the eight, whether they are flashing |
| ATTR | (line, column) | then | Command | Produces sound from the computer's speaker; line is in seconds, pitch is in above (positive value) or below (negative value) middle C |
| column | BEEP | then | Other | Indicates duration, pitch is in Binary number |
| duration | BIN | Command | Sets the border of the screen to the colour specified by the number | |
| number | BORDER | then | Command/other | Makes all following colours brighter if number is 1, or its normal shade if 0 |
| number | BRIGHT | then | Command | Displays contents of ZX Microdrive specified by number |
| number | CAT | then | Function | Returns the character corresponding to the decimal number in the computer's character set |
| number | CHR$ | then | Command | Draws a circle with its centre at coordinates (number,number) and radius CIRCLE |
| x, y, r | x | Command | Clears the screen, all variables and the y stack, and optionally sets the maximum RAM address to be used by BASIC | |
| r | CLEAR | then | Command | Closes the specified stream number for access |
| address | Command | Clears all text and graphics from the screen | ||
| GO SUB | CLOSE # | then | Function/other | Returns the number corresponding to the first character in number in the computer's character set; also used to save arbitrary chunks memory to tape, disk, etc. and load them back in – see CLS, CODE and string for details |
| string | Command | Restarts a program after it has stopped due to an error or the user pressing the or keys | ||
| LOAD | Command | Sends the currently displayed screen to the printer | ||
| SAVE | VERIFY | then | Function | Returns the cosine of CONTINUE |
| COPY | COS | then | Command/other | Provides numbers and/or strings to use with the number command and allows saving the contents of an array to tape when used with the number command (as DATA) |
| comma-separated values | READ | then | Command | Defines a custom function that can be used with the SAVE command;function definitions must be of the form SAVE filename DATA array name(), for example DEF FN and the function name may not consist of more than one letter, plus a $-symbol if the function returns a string |
| name(variable) = operation | FN | Command | Declares an array with the specified f(x)=operations, which may be multi-dimensional (for example, f(x)=x*2; if used with strings, the last dimension indicates the length of each of the strings (thus, DIM is an array of two strings each of five characters long, and variable(dimensions) is one string of five characters) | |
| dimensions | DIM a(10,10) | Command | Draws a line in the current DIM A$(2,5) colour to coordinates (DIM B$(5),DRAW) from the coordinates used by the previous x, y [, r] or INK command; if the optional x is supplied, it indicates the angle of the circle segment to be drawn, in | |
| y | PLOT | then | Command | Deletes the specified file from a ZX Microdrive |
| DRAW | r | then | Function | Returns e to the power ERASE |
| drive;"filename" | EXP | then | Command/other | Makes all following text alternate its foreground (number) and background (number) colours |
| FLASH | number | then | Function | Calls the INK defined earlier in the program using PAPER |
| FN | function(value) | then | Command | Formats the cartridge in the indicated ZX Microdrive and assigns it the identifier function |
| DEF FN | FORMAT | Command | Starts a drive;"name"-name loop; the variable name may only be one character long | |
| FOR | variable = start TO end | Command | Makes the program jump to the BASIC line specified by FOR; when the program encounters the command NEXT, it will jump back to the statement after the GO SUB | |
| number | number | Command | Makes the program jump to the BASIC line specified by RETURN | |
| GO SUB | GO TO | Command | Evaluates the number, and if true, executes the statement that follows the keyword number that must come after the condition, for example | |
| IF | condition THEN | then | Function | Returns a byte read from the hardware input/output port corresponding to the condition |
| THEN | IN | then | Command/other | Sets the foreground colour for text and graphics |
| address | address | then | Function | Returns a string representing the key being pressed on the keyboard at the moment the function is called, or an empty string if none is, but does not wait for a keypress |
| INK | number | Command | Halts program execution until the user types in something on the keyboard and presses the INKEY$ key, then stores the entered value in the specified ; if the optional INPUT is supplied, this will be shown on the screen | |
| [prompt,] variable | Enter | then | Function | Returns the integer value of variable, rounding down to the nearest whole number (thus, prompt returns −2, not −1) |
| INT | number | then | Command/other | Reverses the colours on all following text if number is 1, so that it uses the current ink colour for the background and the current paper colour for the text, or sets them back to normal if INT -1.1 is 0 |
| INVERSE | number | then | Function | Returns the number of characters (bytes) in number |
| number | LEN | Command | Assigns string to the named variable | |
| string | LET | then | Other |
|
| LINE | Command | Outputs the current BASIC program to the screen; if the optional INPUT is provided, it omits all lines with a lower number | ||
| SAVE | LIST | then | Command | As [number] except the listing is output to the printer |
| number | LLIST | then | Function | Returns the natural logarithm of [number] |
| LIST | LN | Command | Loads from tape or another storage device, with the number specified, or the first file found if an empty string (number) is provided.
| |
| filename | "" | then | Command | As variable() except output is sent to the printer |
| length | LPRINT | then | Command | As text, except it does not delete the current program and variables; if a line number exists in both, that of the newly loaded program overwrites the existing one. Using PRINT prevents a program saved using MERGE from auto-running once loaded |
| "[filename]" | LOAD | then | Command | Moves data from one stream (keyboard, screen, file, printer, network, etc.) to another |
| MERGE | Command | Erases the current BASIC program and all variables | ||
| LINE | MOVE | Command | Closes a stream1 TO stream2-NEW loop; the variable must match that of the corresponding NEXT command – "empty" variables to refer to the immediately preceding FOR in the program are not allowed | |
| NEXT | FOR | Logical operator | Returns true if the NEXT is false, else returns false | |
| FOR | NOT | then | Command | Opens a stream for reading from and/or writing to |
| condition | Logical operator | Returns true if either of the conditions on either side of the condition keyword are true, else returns false | ||
| OPEN # | stream | then | Command | Sends the OR (a byte) to the hardware input/output port corresponding to the OR. |
| OUT | address, value | then | Command/other | Will make following text overprint with an XOR operation what is already on the screen if value is 1, instead of erasing it, or erase it if address is 0 |
| OVER | number | then | Command/other | Sets the background colour for text and graphics |
| number | number | Command | Halts program execution for the specified delay, in of a second in Europe or in North America (thus, PAPER halts for one second in Europe). Also continues after a key press. | |
| number | PAUSE | then | Function | Returns a byte representing the contents of the memory location pointed to by delay |
| PAUSE 50 | PEEK | then | Function | Returns the value of pi |
| address | address | Command | Draws a pixel in the current PI colour on the screen at the coordinates (,PLOT) | |
| x, y | INK | then | Function | Returns 1 if the pixel pointed at graphical coordinates (x,y) is currently in the ink (foreground) colour, else returns 0 |
| POINT | (x,y) | Command | Sets the contents of x in RAM to y | |
| POKE | address, value | Command | Prints address (which must be one or more strings or numbers separated with semicolons) to the screen. If used with #0 or #1, it prints in the bottom two (input) lines of the screen; if used with value, it prints at the specified text coordinates; otherwise, it prints either immediately following the output of any previous PRINT statement (if the previous statement ended in a semicolon), or in the first column of the line below the previous [AT x,y;] text output, defaulting to 0,0. | |
| text | AT | Command | Initializes the random number generator; if used without a PRINT (or with 0), it does this based on the computer's internal clock, else it uses the PRINT supplied, which must be in the range 1,65535 | |
| RANDOMIZE | [number] | then | Command | Takes a value from a number statement and stores it in the named number: the first time READ is used, it gets the first value after the first variable, the second time it gets the next one, and so on |
| DATA | text | Command | Begins a comment in the source code, meaning that everything after the variable statement is ignored, until the end of the line – note this includes everything after a colon, which normally begins a new segment: will not produce any output, for example. | |
| READ | DATA | then | Command | Resets where REM commands look for values in REM statements: if used without a number, the next RESTORE will use the first [number] in the program, with a number it will use the first READ on or after the line whose number is indicated |
| DATA | Command | Returns execution to the first statement following the last READ command that was executed | ||
| DATA | DATA | then | Function | Returns a pseudo-random number with eight significant figures in the range [0,1) |
| RETURN | GO SUB | Command | Starts the current BASIC program, from its first line if no RND is specified, else from the line with that number (or the first one after, if it does not exist) | |
| RUN | Command | Saves to tape or another storage device, with the [number] specified.
| ||
| "filename" [DATA variable() {{pipe}}<nowiki></nowiki> | filename | then + | Function/other | As a function, identifies the character at the specified line and column on the screen. Used after the filename in a LINE or LOAD command, indicates that the contents of the display memory should be loaded or saved; this essentially makes it a shortcut for SCREEN$The Spectrum’s display memory starts at address 16384 and is 6912 bytes long. but does not work with [(line, column)] because the contents of the display memory will be different by the time that command reads back the saved data; |
| LOAD | SAVE | then | Function | Returns 1 if CODE 16384,6912 is positive, 0 if it is 0, and −1 if it is negative |
| VERIFY | SGN | then | Function | Returns the sine of number |
| number | SIN | Other | Indicates the interval used by a number statement, for example will skip number and STEP in the loop | |
| number | Command | Ends execution of the current program, exiting to the BASIC editor; can also be given when the computer is waiting for input using the FOR command; once the program is stopped, it can be resumed with n=3 | ||
| n=5 | STOP | then | Function | Returns the square root of INPUT |
| CONTINUE | SQR | then | Function | Converts a number to string. |
| number | number | then | Other | In a STR$ statement, makes sure that the text to be output begins in the column specified, wrapping to the next line as necessary, but never more than one line |
| number | TAB | then | Function | Returns the tangent of column |
| TAN | Other | Follows the condition in an number statement to indicate what should happen when the condition evaluates to true | ||
| number | THEN | Other | Indicates a range from the number to the left of statement to the number of the right of it, inclusive; when used with IF both numbers must be supplied, while if used to slice strings, either may be left off to indicate the start or end of the string | |
| TO | then | Function | When called with a single-character string, this returns the memory address at which the glyph for the user-defined graphic character corresponding to that character is defined. If called with an address, it starts machine code execution at that address (thus making it one of the few Sinclair BASIC functions to have a Side effect) and returns the contents of the Z80’s BC register pair. | |
| TO | FOR | then | Function | Evaluates the USR as a number and returns the result; this can perform calculations: string or address returns 3, for example, and also evaluates variables and even other VAL statements: A string inside a string must have its quotes doubled in Sinclair BASIC. also returns 3 |
| string | string | then | Function | Similar to VAL "1+2" but evaluates the string as a string |
| VAL | VAL$ | then | Command | Reads a program or data from tape or other storage, much like string, but instead of loading it into memory, compares it with the program or data that is already in memory. This is intended to be used immediately after a VAL command, to make sure the program or data has been saved without corruption. |
|
|